package com.eascs.banknet.boc.service.trans;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.jdom.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.banknet.boc.dao.BOCS02Dao;
import com.eascs.banknet.boc.service.BOCAbstractService;
import com.eascs.banknet.boc.vo.bocs02.BOCS02Bean;
import com.eascs.banknet.boc.vo.bocs02.BOCS02Element;
import com.eascs.banknet.boc.vo.bocs02.BOCS02Root;
import com.eascs.banknet.common.utils.XmlHelp;
import com.eascs.banknet.constant.EAContant;
import com.eascs.banknet.log.entity.LogEntity;
import com.eascs.common.util.StringUtil;

/**
 * 借款合同及借据生成
 * @author Administrator
 *
 */
@Service("bocS02Service")
public class BOCS02Service extends BOCAbstractService{
	private static final Logger logger = LoggerFactory.getLogger(BOCS02Service.class);
	@Autowired
	private BOCS02Dao bocS02Dao;
	
	private String startId;
	
	@Override
	public LogEntity initLogData() {
		LogEntity logEntity = new LogEntity();
		logEntity.setBankType(LogEntity.BANK_TYPE_BOC);
		logEntity.setTransType("S02");
		logEntity.setTypeName("借款合同及借据生成");
		logEntity.setStartTime(new Date());
		return logEntity;
	}
	

	@Override
	public Map<String, String> dowork() {
		Map<String, String> result = new HashMap<>();
		String id = "";
		String loanapplyNo = "";
		LogEntity logEntity = initLogData();
		try {
			logger.info("借款合同及借据生成调用开始，startId:[{}]", startId);
			/**
			 * 获取业务数据，组装xml消息
			 */
			BOCS02Element element = null;
			while(null == element){
				//查询需要申请贷款的数据
				BOCS02Bean bean = bocS02Dao.queryData(startId);
				if(null == bean){
					startId = null;
					logger.info("借款合同及借据生成,没有符合条件的数据");
					return null;
				}
				id = bean.getAPPNO();
				loanapplyNo = loanapplyDao.getLoanapplyNoByAppno(id);
				startId = id;
				//查询贷款人CRM资料,若不完整则记录日志并跳过
				element = bocS02Dao.joinCrmInfo(bean);
				if(null == element){
					logger.error("客户信息不完整,appno:[{}], customer_id:[{}]", id, bean.getCustomerId());
					logService.writeLog(logEntity, id, LogEntity.RESULT_TYPE_ERROR, "客户资料不完整，请检查客户和门店信息");
				}else{
					String checkMsg = bocS02Dao.checkElement(element);
					if(StringUtil.hasText(checkMsg)){
						logger.error("申请人信息不完整,appno:[{}], customer_id:[{}]， checkMsg:[{}]", id, bean.getCustomerId(), checkMsg);
						logService.writeLog(logEntity, id, LogEntity.RESULT_TYPE_ERROR, checkMsg);
						element = null;
					}
				}
			}
			BOCS02Root root = new BOCS02Root();
			root.getBody().setElement(element);
			String xml = XmlHelp.convertToXml(root);
			XmlHelp.createXml("S02" + "(" + loanapplyNo + ")", loanapplyNo + "&" + XmlHelp.convertToXml(root), "BOCS02RQ", bocUtil.getEaFtpInfo());
			
			/*
			 * 调用中行接口
			 */
			logger.info("组装XML请求完成，调用中行S02接口, id:{},xml:{}", id, xml);
			String returnXml = bocNetService.executeSocket(bocUtil.getBocSocketInfo(), "S02", null, xml);
			if(StringUtil.isEmpty(returnXml)){
				logger.error("中行S02接口返回数据为空！");
				throw new Exception("中行S02接口返回数据为空");
			}
			logger.info("中行S02接口返回xml完成, returnXml：{}", returnXml);
			
			/**
			 * 解析返回xml，保存数据
			 */
			XmlHelp.createXml("S02"+"("+loanapplyNo+")",returnXml,"BOCS02RS", bocUtil.getEaFtpInfo());
			Element rsRoot = XmlHelp.getRootByString(returnXml);
			Element head = rsRoot.getChild("HEADER");
			Element body = rsRoot.getChild("BODY");
			String trncod_rs = head.getChildText("RETCODE")==null?"":head.getChildText("RETCODE");
			if (!EAContant.BOC001RS.equals(trncod_rs.toLowerCase())) {
				String note = head.getChildText("NOTE");
				if(StringUtil.isEmpty(note)){
					//NOTE内容包含换行时获取不到内容，用字符串截取
					note = StringUtils.substringBetween(returnXml, "<NOTE>", "</NOTE>");
				}
				throw new Exception(note);
			}
			String osn = head.getChildText("OSN");
			Element trn = body.getChild("OUTPUT");
			int rw = bocS02Dao.updateInfo(id, osn);
			if(rw <= 0){
				throw new Exception("更新中行BOCS02接口结果失败");
			}
			//String appno = trn.getChildText("APPNO");
			logService.writeLog(logEntity, id, LogEntity.RESULT_TYPE_SUCCESS, null);
		} catch (Exception e) {
			logger.error("借款合同及借据生成出现异常，id：[{}]，errMsg：[{}]", id,  e.getMessage());
			logService.writeLog(logEntity, id, LogEntity.RESULT_TYPE_ERROR, e.getMessage());
			e.printStackTrace();
		}
		return result;
	}
}
